from django.shortcuts import render
from . import models
from .serializers import UserMobileSerializer
from rest_framework.generics import CreateAPIView
from rest_framework import status
import re
import random
from django_redis import get_redis_connection
from lufffyapi.settings import constants
from lufffyapi.libs.yuntongxun import sms

# Create your views here.


pc_geetest_id = "5e876edb2bda195c265416b70e7389a7"
pc_geetest_key = "c1f0f6f5958507924d187db31cd136e5"

from lufffyapi.utils.geetest import GeetestLib
from rest_framework.response import Response
from .utils import get_user_by_account
from rest_framework.views import APIView
from rest_framework import status as http_status


class CaptchAPIView(APIView):
    status = 1
    user_id = 'test'

    def get(self, request):
        username = request.query_params.get('username')
        user = get_user_by_account(username)
        if user is None:
            print(user)
            return Response({"message": "对不起，用户不符"}, status=http_status.HTTP_400_BAD_REQUEST)
        self.user_id = user.id
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        self.status = gt.pre_process(self.user_id)
        response_id = gt.get_response_str()
        # print(response_id)
        return Response(response_id)

    def post(self, request):
        gt = GeetestLib(pc_geetest_id, pc_geetest_key)
        challenge = request.POST.get(gt.FN_CHALLENGE, '')
        validate = request.POST.get(gt.FN_VALIDATE, '')
        seccode = request.POST.get(gt.FN_SECCODE, '')
        print(self.status)
        if self.status:
            print('yes')
            result = 1
            # result = gt.success_validate(challenge, validate, seccode, self.user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)
        print(result)
        result = {"status": "success"} if result else {"status": "fail"}
        print(result)
        return Response(result)


class UserAPIView(CreateAPIView):
    queryset = models.User.objects.all()
    serializer_class = UserMobileSerializer


class MobileAPIView(APIView):
    def get(self, request, mobile):
        if re.match(r'1[3,9]\d{9}', mobile):
            return Response({"msg": "ok"})
        return Response({"msg": "抱歉，手机号有误，请重新输入"}, status=http_status.HTTP_400_BAD_REQUEST)


class SmsAPIView(APIView):
    def get(self, request, mobile):
        print(mobile)
        redis_conn = get_redis_connection('sms_code')
        check_ret = redis_conn.get(f"mobile_{mobile}")
        # print(redis_conn)
        #
        # print(check_ret)
        if check_ret is not None:
            return Response({'msg': "60秒内已经发送了过了，请稍后再试。"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
        try:
            sms_code = "%06d" % random.randint(0, 999999)
            print(sms_code)
            redis_conn.setex(f"sms_{mobile}", constants.SMS_EXPIRE_TIME, sms_code)
            redis_conn.setex(f"mobile_{mobile}", constants.SMS_EXPIRE_TIME, '_')
            # todo
            from mycelery.sms import tasks
            tasks.send_sms.delay(mobile, sms_code)
            return Response('短信发送成功')

        except:
            return Response({"msg": "服务器内部错误"}, status=http_status.HTTP_500_INTERNAL_SERVER_ERROR)
